import pymysql

from oms import settings


class mysql_helper(object):
    def __init__(self, conn):
        self.host = conn['HOST']
        self.user = conn['USER']
        self.password = conn['PASSWORD']
        self.db = conn['NAME']
        self.port = int(conn['PORT'])
        self.charset = 'uft8'

    def mysql_command(self, sql_cmd):  # 执行sql
        try:
            ret = []
            conn = pymysql.connect(host=self.host, user=self.user, passwd=self.password, db=self.db,
                                   port=self.port, charset="utf8")
            cursor = conn.cursor()
            n = cursor.execute(sql_cmd)
            for row in cursor.fetchall():
                for i in row:
                    ret.append(i)
            conn.commit()
            cursor.close()
            conn.close()
        except pymysql.Error as e:
            ret.append(e)

        return ret

    def select_table(self, sql_cmd, parmas):  # 执行带参数的sql
        try:
            ret = []
            conn = pymysql.connect(host=self.host, user=self.user, passwd=self.password, db=self.db,
                                   port=self.port, charset="utf8")
            cursor = conn.cursor()
            n = cursor.execute(sql_cmd, parmas)
            for row in cursor.fetchall():
                for i in row:
                    ret.append(i)
            conn.commit()
            cursor.close()
            conn.close()
        except pymysql.Error as e:
            ret.append(e)
        return ret
